package xlsx

import (
	"github.com/pkg/errors"
	"github.com/xuri/excelize/v2"
	"path/filepath"
	"stock/server/dao"
	"stock/server/internal/pkg/pathulit"
)

type Option struct {
	FilePath string
	excelize.Options
}

type Xlsx struct {
	f *excelize.File
}

var _ dao.DBInterface = (*Xlsx)(nil)

func (o *Xlsx) Group() map[string][]string {
	//TODO implement me
	panic("implement me")
}

// Open 打开 xlsx 文件
// option: Option
func (o *Xlsx) Open(option any) (dao.DBInterface, error) {
	var opt Option
	if option != nil {
		opt = option.(Option)
	}

	exePath, err := pathulit.ExePath()
	if err != nil {
		return nil, err
	}

	o.f, err = excelize.OpenFile(filepath.Join(exePath, opt.FilePath), opt.Options)
	if err != nil {
		return nil, errors.Wrap(err, "打开 xlsx 文件")
	}

	return o, nil
}

// CodeInfo 获取股票代码
func (o *Xlsx) CodeInfo() map[string]dao.StockInfo {
	data := make(map[string]dao.StockInfo)

	sheetName := "股池"
	rows, _ := o.f.GetRows(sheetName)
	for i, row := range rows {
		if i == 0 {
			continue
		}

		// 交易所
		exchange := o.getCol(row, 3)
		// 股票代码
		code := exchange + o.getCol(row, 1)
		// 股票名称
		title := o.getCol(row, 0)
		// 股票简称
		abbreviation := o.getCol(row, 2)
		// 交易周期
		tradingPeriod := o.getCol(row, 4)
		// 股票类型
		typ := o.getCol(row, 5)

		info := dao.StockInfo{
			Code:          code,
			Title:         title,
			Abbreviation:  abbreviation,
			Exchange:      exchange,
			TradingPeriod: tradingPeriod,
			Type:          typ,
		}

		data[code] = info
	}

	return data
}

func (o *Xlsx) getCol(row []string, idx int) string {
	if len(row) <= idx {
		return ""
	}

	return row[idx]
}
